export const get_ffmpeg_code = (inputFiles, outputName) => {
  let ffmpegCommand = ["-i", "background.mp3"];

  let filterComplex = "";
  for (let i = 0; i < inputFiles.length; i++) {
    ffmpegCommand.push("-i", inputFiles[i]);
    filterComplex += `[${i}:v]`;
  }
  filterComplex += `concat=n=${inputFiles.length}:v=1:a=0[v];`;

  ffmpegCommand.push(
    "-filter_complex",
    filterComplex + "[v][0:v]overlay[outv]",
    "[outv]",
    outputName
  );
  return ffmpegCommand;
};

export const get_duration = async (file) => {
  if (!file) return;
  let blob = new Blob([file], { type: "video/mp4" });
  let src = URL.createObjectURL(blob);
  return new Promise((resolve, reject) => {
    const video = document.createElement("video");
    video.preload = "metadata";
    video.onloadedmetadata = async () => {
      URL.revokeObjectURL(src);
      video.remove();
      const duration = video.duration;
      resolve(duration);
    };
    video.onerror = () => {
      URL.revokeObjectURL(src);
      video.remove();
      reject("Failed to load video");
    };
    video.src = src;
  });
};

function timeToSeconds(timeStr) {
  const parts = timeStr.split(':');
  const hours = parseInt(parts[0], 10) || 0;
  const minutes = parseInt(parts[1], 10) || 0;
  const seconds = parseFloat(parts[2]) || 0;

  return hours * 3600 + minutes * 60 + seconds;
}

export function extractDuration(inputStr) {
  // 使用正则表达式匹配时长信息
  const durationRegex = /Duration: (\d{2}:\d{2}:\d{2}.\d+)/;
  const match = inputStr.match(durationRegex);

  if (match) {
    const durationStr = match[1]; // 提取匹配到的时长字符串
    console.log('ddddd',durationStr)
    return timeToSeconds(durationStr); // 调用之前定义的转换函数
  } else {
    return 0; // 如果未匹配到时长信息，返回 null 或者其他适当的值
  }
}

export async function saveBlobVideo(buffer, fileName, filePath) {
  const result = await window.ipcRenderer.invoke(
    "local-video",
    buffer,
    fileName,
    filePath
  );
  if (!result) {
    return;
  }
  return new Promise((resolve) => {
    resolve(result);
  });
}